<script setup>
import { ref } from 'vue'
import axios from 'axios'
const messages = ref([]) // 初始欢迎消息
const inputMessage = ref('')
const loading = ref()
const sendMessage = async () => {
  if (inputMessage.value.trim() !== '') {
    messages.value.push({ role: 'user', content: inputMessage.value })
    try {
      //获取access_token,有效期30天
      // const response = await axios.post(
      //   'oauth/2.0/token?grant_type=client_credentials&client_id=to2FBdFpcdd7cCkzzFjVOPrn&client_secret=G7kSTlFsQAUM4JRHYdVI3KZSHhqGPQkG',
      //   {
      //     message: inputMessage.value
      //   },
      //   {
      //     headers: {
      //       'Content-Type': 'application/json',
      //       Accept: 'application/json'
      //     }
      //   }
      // )
      // console.log(response)
      loading.value = true
      inputMessage.value = ''
      const response = await axios.post(
        'rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=24.f1873502c05896048bfbd76614c88af3.2592000.1717601652.282335-59280492',
        {
          messages: messages.value
        },
        {
          headers: {
            'Content-Type': 'application/json'
          }
        }
      )
      messages.value.push({
        role: 'assistant',
        content: response.data.result
      })
    } catch (error) {
      console.error('Error sending message:', error)
    } finally {
      loading.value = false
    }
  }
}
</script>

<template>
  <div class="chat-container">
    <div class="chat-messages">
      <el-card
        v-for="(message, index) in messages"
        :key="index"
        :class="{
          'sent-message': message.role === 'user',
          'received-message': message.role === 'assistant'
        }"
      >
        <p>{{ message.content }}</p>
      </el-card>
    </div>
    <div class="chat-input">
      <el-input v-model="inputMessage" placeholder="请输入消息"></el-input>
      <el-button :loading="loading" @click="sendMessage" type="primary"
        >发送</el-button
      >
    </div>
  </div>
</template>
<style scoped>
.chat-container {
  width: 700px;
  margin: 0 auto;
  margin-top: 50px;
  border: 1px solid #ccc;
  border-radius: 10px;
  overflow: hidden;
}

.chat-messages {
  height: 300px;
  overflow-y: auto;
  padding: 10px;
}

.message {
  margin-bottom: 10px;
}

.sent-message {
  background-color: #409eff;
  color: #fff;
  padding: 5px 10px;
  border-radius: 4px;
  align-self: flex-end;
}

.received-message {
  background-color: #f0f0f0;
  padding: 5px 10px;
  border-radius: 4px;
}

.chat-input {
  display: flex;
  align-items: center;
  padding: 10px;
}
</style>
